/**
 * Copyright 2012 ibiblio
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.ibiblio.terasaur.bt

/**
 * Delete torrent
 *
 * check for valid info hash
 * if not, set error message and follow redirect logic
 * check that torrent exists
 * if not, set error message and follow redirect logic
 * delete torrent
 * if torrent delete not okay:
 *      log error
 *      set error message
 *      follow redirect logic
 * check for torrent file
 * if not (which shouldn't ever happen):
 *		log error
 * follow redirect logic
 *
 * redirect logic:
 *      if valid item, redirect back to item page
 *      else if valid torrent, redirect to torrent show page
 *      else, redirect to torrent show page
 */
class TorrentServiceDeleteCommand {
    private _service
    private _torrent
    private _item

    TorrentServiceDeleteCommand(Map params) {
        _service = params.service
        _torrent = params.torrent
        _item = params.item
    }

    public Map run() {
        Map result
        if (_torrent && _item) {
            if (_isSeeded(_torrent)) {
                result = [messageCode: 'torrent.delete.error.has_seeds']
            } else {
                Map transactionResult
                Torrent.withTransaction { status ->
                    result = this._transaction(_torrent)
                    if (result.success) {
                        // Update search index
                        _service.searchService.add(_item)
                    } else {
                        status.setRollbackOnly()
                    }
                }
            }
        } else {
            _service.log.error("Missing torrent or item")
            result = [messageCode: 'torrent.delete.error.general']
        }
        return result
    }

    private boolean _isSeeded(Torrent torrent) {
        if (torrent?.seedbanks?.size() > 0) {
            return true
        } else {
            return false
        }
    }

    private Map _transaction(Torrent torrent) {
        TorrentFileManager fm = _service._getTorrentFileManager()
        Map result = [success:true]

        try {
            torrent.delete(flush:true)
            fm.remove(torrent.infoHash)
        } catch (FileNotFoundException e) {
            _service.log.error("Missing torrent file after deleting torrent (info_hash: " + torrent.infoHash + ", name: " + torrent.name + ")")
        } catch (Exception e) {
            _service.log.error("Torrent delete exception (" + e.class.name + "): " + e.message)
            result.messageCode = 'torrent.delete.error.general'
            result.success = false
        }

        if (result.success) {
            result.messageCode = 'torrent.delete.success.message'
        }
        return result
    }

}
